
import { ref } from 'vue';

export function useWebSocket() {
  const ws = ref(null);
  const messages = ref([]);
  const isConnected = ref(false);

  // 连接 WebSocket 服务
  const connect = () => {
    ws.value = new WebSocket('ws://localhost:8080');

    // 连接成功后
    ws.value.onopen = () => {
      console.log('WebSocket connected');
      isConnected.value = true;
    };

    // 接收消息
    ws.value.onmessage = (event) => {
      const message = JSON.parse(event.data);
      messages.value.push(message);
    };

    // 监听关闭
    ws.value.onclose = () => {
      console.log('WebSocket disconnected');
      isConnected.value = false;
      reconnect(); // 断线重连
    };

    // 监听错误
    ws.value.onerror = (err) => {
      console.error('WebSocket error:', err);
    };
  };

  // 发送消息
  const sendMessage = (message) => {
    if (ws.value && ws.value.readyState === WebSocket.OPEN) {
      ws.value.send(JSON.stringify({ type: 'message', content: message }));
    }
  };

  // 断线重连机制
  const reconnect = () => {
    setTimeout(() => {
      console.log('Reconnecting to WebSocket server...');
      connect();
    }, 5000); // 5秒后重新连接
  };

  return {
    ws,
    messages,
    isConnected,
    connect,
    sendMessage
  };
}
// src/websocket.js

class WebSocketService {
  constructor(url) {
    this.url = url;
    this.socket = null;
    this.callbacks = {};
  }

  connect() {
    this.socket = new WebSocket(this.url);

    this.socket.onopen = () => {
      console.log('WebSocket connection opened');
    };

    this.socket.onclose = () => {
      console.log('WebSocket connection closed');
    };

    this.socket.onerror = (error) => {
      console.error('WebSocket error:', error);
    };

    this.socket.onmessage = (event) => {
      const message = JSON.parse(event.data);
      if (this.callbacks[message.type]) {
        this.callbacks[message.type](message.data);
      }
    };
  }

  sendMessage(type, data) {
    if (this.socket && this.socket.readyState === WebSocket.OPEN) {
      this.socket.send(JSON.stringify({ type, data }));
    } else {
      console.error('WebSocket is not open');
    }
  }


  on(type, callback) {
    this.callbacks[type] = callback;
  }

  close() {
    if (this.socket) {
      this.socket.close();
    }
  }
}

export default WebSocketService;
